package wxgrobot

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
)

type MentionedOption struct {
	userIdList []string
	mobileList []string
}

func NewEmptyOption() *MentionedOption {
	return &MentionedOption{[]string{}, []string{}}
}

func NewMentionAllOption() *MentionedOption {
	return &MentionedOption{[]string{"@all"}, []string{}}
}

func NewMentionMobileOption(mobileList ...string) *MentionedOption {
	return &MentionedOption{[]string{}, mobileList}
}

func SendTextMsg(key string, content string, mentionedOption *MentionedOption) bool {
	return sendMsg(key, "text", content, mentionedOption)
}

func SendMarkdownMsg(key string, content string, mentionedOption *MentionedOption) bool {
	return sendMsg(key, "markdown", content, mentionedOption)
}

func sendMsg(key string, typeStr string, content string, mentionedOption *MentionedOption) bool {
	b1, _ := json.Marshal(mentionedOption.userIdList)
	b2, _ := json.Marshal(mentionedOption.mobileList)
	dataJsonStr := fmt.Sprintf(`{"msgtype": "%s", "%s": {"content": "%s", "mentioned_list": %s, "mentioned_mobile_list": %s}}`, typeStr, typeStr, content, string(b1), string(b2))
	fmt.Println(dataJsonStr)

	resp, err := http.Post(
		fmt.Sprintf(`https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=%s`, key),
		"application/json",
		bytes.NewBuffer([]byte(dataJsonStr)))

	if err != nil {
		return false
	} else {
		defer resp.Body.Close()
		return true
	}
}
